package com.example.kotlindemo_room

import android.content.Intent
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.activity_main.*

/**
 * jetpack  Room示例
 *
 * entity  实体类，对应表 使用注解@Entity标记
 * Dao     包含访问数据库的方法，使用注解@Dao标记
 * Database 数据库持有者，使用注解@Database标记
 */
class MainActivity : AppCompatActivity() {

    lateinit var studentDao: StudentDao

    lateinit var studentViewModel: StudentViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val instance = MyDataBase.getInstance(this)

        studentDao = instance.getStudentDao()



        studentViewModel =
            ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application)).get(
                StudentViewModel::class.java
            )


        studentViewModel.getAllStuDentLive()?.observe(this, Observer {
            Log.d("MainActivity", "111" + it.toString())
            tv1.setText(it.toString())
        })


        btn1.setOnClickListener {
            studentViewModel.InsertStuDent()
            studentViewModel.InsertStuDent2(Student())
//            btn1.postDelayed(Runnable {
//                studentViewModel.InsertStuDent2(Student(100,"无名",23))
//            },1000)
//            InsertStuTask(studentDao).start()
        }

        btn2.setOnClickListener {
            studentViewModel.DeleteStuDent(Student(1,"张三",20))
        }
        btn3.setOnClickListener {
            studentViewModel.UpDateStuDent(Student(2,"张三",21))
        }
        btn4.setOnClickListener {
//            getAllStuTask(studentDao).start()
            startActivity(Intent(this, MainActivity2::class.java))
        }
        btn5.setOnClickListener {
            //清空数据库
            studentViewModel.DeleteAllStuDent()
        }
    }



}